﻿package com.chee.plant.logic.user;

import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import org.hibernate.Query;
import org.hibernate.Session;

import com.chee.plant.hibernate.object.User;
import com.chee.plant.logic.CmdHandler;
import com.chee.plant.logic.PlantCmd;
import com.chee.plant.server.CommonData;
import com.chee.plant.server.HibernateSessionFactory;
import com.chee.plant.server.Message;
import com.chee.plant.server.SessionEntity;

public class UserLoginHandler implements CmdHandler {

	@Override
	public Vector<Message> executeCmd(Message msg) {
		// region_1: 这段代码是解析客户端传输来的内容的,具体的内容格式是和客户端商定好的
		// 假设商定的客户端传过来的登录请求的内容分几段, 分别是 :
		// username=xxx password=xxxx
		Vector<Message> _msgs = new Vector<Message>();
		String username = (String) msg.getData("username");
		String password = (String) msg.getData("password");
		// end of region_1

		// region_2: do database operations
		Session sess = HibernateSessionFactory.getSession();
		String sql = String.format("from User usr where name='%1$s'", username);
		Query query = sess.createQuery(sql);
		User usr = (User) query.uniqueResult();
		Date tm = Calendar.getInstance().getTime();
		String ip = msg.getSession().getLocalAddress().toString();
		if (usr == null) {
			// new user, add to database
			usr = new User();
			usr.setDefaults();
			usr.setName(username);
			usr.setPassword(password);
			usr.setCreateIp(ip);
			usr.setCreated(tm);
		} else {
			// if not new user, do nothing..
		}
		usr.setLoginIp(ip);
		usr.setLoginTime(tm);
		sess.save(usr);
		sess.flush();

		int userId = usr.getId();
		int result = 1;
		// check if user has logged in, if so, tick the former one, use the
		// latter one
		SessionEntity entity = CommonData.getSession(userId);
		if (entity != null && !entity.isSession(msg.getSession())) {
			CommonData.removeSession(userId);
		}
		boolean loginResult = CommonData.setUserForRawSession(msg.getSession(),
				userId);
		String content = "login success";
		if (!loginResult)
			content = "you are already logged";
		Message ret = new Message(userId, PlantCmd.Login, result);
		ret.addVariable("message", content);
		_msgs.add(ret);
		return _msgs;
	}

}
